<?php
\Log::error("自动升级");
$c = $_GET['code'];
$u = $_SERVER['HTTP_HOST'];
$a = 'download';
$b = "one"; //每次请求安装全部版本,参数填 all, 每次安装一个版本 one

//下载当前已安装的下一版本
$url = 'https://www.kt8.cn/cloud/apiauthsys/index?a='.$a."&u=".$u."&c=".$c;
if($b == 'one'){
	$res = insta($url);
	exit($res);
}else if($b == 'all'){
	$msg = '';
	while (1) {
		$res = insta($url);
		if($res!="success"){
			$msg = $res['msg'];
			break;
		}

	}
	if($msg=="已下载到最新版本"){
		exit('success');
	}else{
		exit($msg);
	}
	
}

function insta($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	$output = curl_exec($ch);
	curl_close($ch);

	$res = json_decode($output,1);
	if($res && $res['status'] == 'success'){
		$resource = $res['data']['resource'];
		$file_name = $res['data']['filename'];
		$field = 'module';
		$path = pub_path('module');
		is_dir($path) or mkdir($path, 0777, true);
		$file_path = $path.'/'.$file_name;
		file_put_contents($file_path, base64_decode($resource));
		$zipFile  = new \Lib\PclZip($file_path);
		$zipPath = dirname(DOXCX_FRAME_PATH);
		$re = $zipFile->extract(PCLZIP_OPT_PATH, $zipPath, PCLZIP_OPT_REPLACE_NEWER);
		if (!$re) \Log::error('解压失败:' . $zipFile->error_string);
		unlink($file_path);
		//去项目根目录找update.sql文件，执行sql
		$sqlPath = DOXCX_FRAME_PATH . '../' . 'update.sql';
		if (file_exists($sqlPath)) {
          $sqlContent = file_get_contents($sqlPath);
          $sqlArr=preg_split("/;[\r\n]+/", $sqlContent);
          foreach($sqlArr as $v){
              db_query($v);
          }
        }
		return 'success';
	}
	return $res['msg'];
}


exit('下载版本失败');